package com.imooc.coupon.controller;

import com.imooc.coupon.exception.CouponException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.serviceregistry.Registration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Administrator
 * @Date 2021/10/27 19:57
 * @Version 1.0
 */
@Slf4j
@RestController
public class HealthCheck {

    @Autowired
    private DiscoveryClient client;

    @Autowired
    private Registration registration;


    /**
     * 健康检查接口
     * 127.0.0.1:7001/coupom-template/health
     *
     * @return
     */
    @GetMapping("/health")
    public String health() {
        log.debug("view health api");
        return "Coupon Template is health";
    }

    /**
     * 异常接口测试
     * 127.0.0.1:7001/coupom-template/exception
     *
     * @return
     */
    @GetMapping("/exception")
    public String exception() throws CouponException {
        log.debug("view exception api");
        throw new CouponException("Coupon Template is exception");
    }

    /**
     * 127.0.0.1:7001/coupom-template/info
     * @return
     * @throws CouponException
     */
    @GetMapping("/info")
    public List<Map<String, Object>> info() throws CouponException {
        List<ServiceInstance> instances = client.getInstances(registration.getServiceId());
        List<Map<String, Object>> result = new ArrayList<>(instances.size());
        instances.forEach(i -> {
            Map<String, Object> info = new HashMap<>();
            info.put("serviceId", i.getServiceId());
            info.put("instanceId", i.getInstanceId());
            info.put("port", i.getPort());
            result.add(info);
        });
        return result;
    }

}
